import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import {
    Layout,
    Card,
    Button,
    Table,
    Modal,
    Form,
    Input,
    Select,
    DatePicker,
    message,
    Tag,
    Alert,
    Spin
} from "antd";
import {
    PlusOutlined,
    NotificationOutlined,
    ClockCircleOutlined
} from "@ant-design/icons";
import axios from "axios";
import { getAuthToken } from "@/router/index.jsx";
import dayjs from "dayjs";

const { RangePicker } = DatePicker;
const { TextArea } = Input;

const ActivityManagement = () => {
    const navigate = useNavigate();
    const [activities, setActivities] = useState([]);
    const [loading, setLoading] = useState(true);
    const [createModalVisible, setCreateModalVisible] = useState(false);
    const [notificationModalVisible, setNotificationModalVisible] = useState(false);
    const [form] = Form.useForm();
    const [notificationForm] = Form.useForm();

    // 获取活动列表
    const fetchActivities = async () => {
        setLoading(true);
        try {
            const response = await axios.get(
                "http://192.168.55.192:8080/api/promotion/active-activities",
                {
                    headers: { Authorization: `${getAuthToken()}` },
                }
            );
            console.log("活动列表响应：", response);
            if (response.data.code === 200) {
                // 确保数据是数组格式
                const activityList = Array.isArray(response.data.data)
                    ? response.data.data
                    : [];
                setActivities(activityList);
            } else {
                message.error(response.data.message || "获取活动列表失败");
            }
        } catch (error) {
            console.error("获取活动列表失败:", error);
            message.error("获取活动列表失败，请检查网络连接");
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchActivities();
    }, []);

    // 创建新活动
    const handleCreateActivity = async (values) => {
        try {
            // 格式化时间
            const formattedValues = {
                ...values,
                startTime: values.timeRange[0].format('YYYY-MM-DDTHH:mm:ss'),
                endTime: values.timeRange[1].format('YYYY-MM-DDTHH:mm:ss'),
                extraConfig: values.extraConfig || "{}",
            };
            delete formattedValues.timeRange;

            console.log("发送的创建活动数据:", formattedValues);

            const response = await axios.post(
                "http://192.168.55.192:8080/api/admin/activity/create",
                formattedValues,
                {
                    headers: { Authorization: `${getAuthToken()}` },
                }
            );

            if (response.data.code === 200) {
                message.success("活动创建成功");
                setCreateModalVisible(false);
                form.resetFields();
                fetchActivities(); // 刷新列表
            } else {
                message.error(response.data.message || "活动创建失败");
            }
        } catch (error) {
            console.error("创建活动失败:", error);
            message.error("创建活动失败，请检查输入");
        }
    };

    // 发送系统通知
    const handleSendNotification = async (values) => {
        try {
            // 使用 URLSearchParams 代替 JSON
            const params = new URLSearchParams();
            params.append('title', values.title);
            params.append('content', values.content);
            params.append('notifyType', 'system'); // 确保包含 notifyType 参数

            console.log("发送的通知数据:", params.toString());

            const response = await axios.post(
                "http://192.168.55.192:8080/api/admin/notification/broadcast",
                params,
                {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded', // 关键修改
                        Authorization: `${getAuthToken()}`
                    },
                }
            );

            if (response.data.code === 200) {
                message.success("系统通知发送成功");
                setNotificationModalVisible(false);
                notificationForm.resetFields();
            } else {
                message.error(response.data.message || "通知发送失败");
            }
        } catch (error) {
            console.error("发送通知失败:", error);
            if (error.response) {
                console.error("后端错误响应:", error.response.data);
                message.error(`发送通知失败: ${error.response.data.message || "未知错误"}`);
            } else {
                message.error("发送通知失败，请检查网络连接");
            }
        }
    };
    // 活动类型标签
    const renderActivityType = (type) => {
        const typeMap = {
            double_upload: { color: "geekblue", text: "双倍上传" },
            free_download: { color: "green", text: "免费下载" },
            discount: { color: "orange", text: "下载折扣" },
        };
        const info = typeMap[type] || { color: "default", text: type };
        return <Tag color={info.color}>{info.text}</Tag>;
    };

    // 活动状态标签
    const renderActivityStatus = (start, end) => {
        const now = dayjs();
        const startTime = dayjs(start);
        const endTime = dayjs(end);

        if (now.isBefore(startTime)) {
            return <Tag color="default">未开始</Tag>;
        }
        if (now.isAfter(endTime)) {
            return <Tag color="gray">已结束</Tag>;
        }
        return <Tag color="success">进行中</Tag>;
    };

    // 活动时间格式化
    const formatActivityTime = (start, end) => {
        const format = "YYYY-MM-DD HH:mm";
        return `${dayjs(start).format(format)} - ${dayjs(end).format(format)}`;
    };

    // 活动列表表格列配置
    const columns = [
        {
            title: "活动名称",
            dataIndex: "activityName",
            key: "activityName",
        },
        {
            title: "活动类型",
            dataIndex: "activityType",
            key: "activityType",
            render: (type) => renderActivityType(type),
        },
        {
            title: "活动时间",
            key: "time",
            render: (_, record) => (
                <>
                    <div>{formatActivityTime(record.startTime, record.endTime)}</div>
                    <div>
                        <ClockCircleOutlined style={{ marginRight: 5 }} />
                        {renderActivityStatus(record.startTime, record.endTime)}
                    </div>
                </>
            ),
        },
        {
            title: "活动描述",
            dataIndex: "description",
            key: "description",
        },
        {
            title: "状态",
            key: "status",
            render: (_, record) => renderActivityStatus(record.startTime, record.endTime),
        },
    ];

    return (
        <Layout className="admin-layout">
            <Content style={{ padding: "24px" }}>
                <Card
                    title="活动管理"
                    extra={
                        <div>
                            <Button
                                type="primary"
                                icon={<PlusOutlined />}
                                style={{ marginRight: 10 }}
                                onClick={() => setCreateModalVisible(true)}
                            >
                                创建新活动
                            </Button>
                            <Button
                                type="dashed"
                                icon={<NotificationOutlined />}
                                onClick={() => setNotificationModalVisible(true)}
                            >
                                发送系统通知
                            </Button>
                        </div>
                    }
                >
                    {activities.length === 0 && !loading && (
                        <Alert
                            message="无活动数据"
                            description="当前没有活动数据，点击上方按钮创建新活动"
                            type="info"
                            showIcon
                            style={{ marginBottom: 16 }}
                        />
                    )}

                    <Table
                        columns={columns}
                        dataSource={activities}
                        loading={loading}
                        rowKey="id"
                        pagination={{ pageSize: 10 }}
                        bordered
                    />
                </Card>

                {/* 创建活动模态框 */}
                <Modal
                    title="创建新活动"
                    open={createModalVisible}
                    onOk={() => form.submit()}
                    onCancel={() => {
                        setCreateModalVisible(false);
                        form.resetFields();
                    }}
                    maskClosable={false}
                    destroyOnClose
                    width={700}
                >
                    <Form
                        form={form}
                        layout="vertical"
                        onFinish={handleCreateActivity}
                        initialValues={{ activityType: "double_upload" }}
                    >
                        <Form.Item
                            label="活动类型"
                            name="activityType"
                            rules={[
                                { required: true, message: "请选择活动类型" },
                            ]}
                        >
                            <Select>
                                <Select.Option value="double_upload">双倍上传</Select.Option>
                                <Select.Option value="free_download">免费下载</Select.Option>
                                <Select.Option value="discount">下载折扣</Select.Option>
                            </Select>
                        </Form.Item>

                        <Form.Item
                            label="活动名称"
                            name="activityName"
                            rules={[
                                { required: true, message: "请输入活动名称" },
                                { max: 50, message: "名称不能超过50个字符" },
                            ]}
                        >
                            <Input placeholder="输入活动名称（不超过50个字符）" />
                        </Form.Item>

                        <Form.Item
                            label="活动时间"
                            name="timeRange"
                            rules={[
                                {
                                    required: true,
                                    type: 'array',
                                    message: "请选择活动时间范围"
                                }
                            ]}
                        >
                            <RangePicker
                                showTime
                                format="YYYY-MM-DD HH:mm"
                                style={{ width: '100%' }}
                            />
                        </Form.Item>

                        <Form.Item
                            label="活动描述"
                            name="description"
                            rules={[
                                { required: true, message: "请输入活动描述" },
                                { max: 200, message: "描述不能超过200个字符" },
                            ]}
                        >
                            <TextArea placeholder="输入活动描述（不超过200个字符）" rows={3} />
                        </Form.Item>

                        <Form.Item
                            label="额外配置 (JSON)"
                            name="extraConfig"
                            extra={
                                <div>
                                    <p>用于存储活动特定的配置信息，支持的配置项：</p>
                                    <ul>
                                        <li>双倍上传: {"{ \"multiplier\": 2 }"}</li>
                                        <li>下载折扣: {"{ \"discountRate\": 0.8 }"}</li>
                                    </ul>
                                </div>
                            }
                        >
                            <TextArea placeholder='例如: {"multiplier":2}' rows={2} />
                        </Form.Item>
                    </Form>
                </Modal>

                {/* 发送系统通知模态框 - 修正版本 */}
                <Modal
                    title="发送系统通知"
                    open={notificationModalVisible}
                    onOk={() => notificationForm.submit()}
                    onCancel={() => {
                        setNotificationModalVisible(false);
                        notificationForm.resetFields();
                    }}
                    maskClosable={false}
                    destroyOnClose
                    width={600}
                >
                    <Form
                        form={notificationForm} // 使用已创建的 form 实例
                        layout="vertical"
                        onFinish={handleSendNotification} // 直接关联处理函数
                    >
                        <Form.Item
                            label="通知标题"
                            name="title"
                            rules={[
                                { required: true, message: "请输入通知标题" },
                                { max: 50, message: "标题不能超过50个字符" },
                            ]}
                        >
                            <Input placeholder="输入通知标题（不超过50个字符）" />
                        </Form.Item>

                        <Form.Item
                            label="通知内容"
                            name="content"
                            rules={[
                                { required: true, message: "请输入通知内容" },
                                { max: 500, message: "内容不能超过500个字符" },
                            ]}
                        >
                            <TextArea placeholder="输入通知内容（不超过500个字符）" rows={4} />
                        </Form.Item>
                    </Form>
                </Modal>
            </Content>
        </Layout>
    );
};

const { Content } = Layout;

export default ActivityManagement;